//
//  UCiEnablerAppDelegate.m
//  UCiEnabler
//
//  Created by Delio Brignoli on 21/07/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "UCiEnablerAppDelegate.h"
#import "RootViewController.h"
#import "IEnablerService.h"
#import "StartupAnimation.h"

@implementation UCiEnablerAppDelegate

@synthesize window;
@synthesize rootViewController;
@synthesize operationQueue;

// +initialize is invoked before the class receives any other messages, so it
// is a good place to set up application defaults
+ (void)initialize {
	
    if ([self class] == [UCiEnablerAppDelegate class]) {
        // Register default values
        NSString *defaultUserName = @"";
        NSString *defaultPassword = @"";
		NSString *defaultAccessState = @"NO";
		
        NSDictionary *resourceDict = [NSDictionary dictionaryWithObjectsAndKeys:UserNameKey,defaultUserName,
									  PasswordKey,defaultPassword,
									  AccessStateKey,defaultAccessState,nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:resourceDict];		
    }
}

- (void)startupAnimationDone:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
	[splashView removeFromSuperview];
	[splashView release];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	[[IEnablerService sharedIEnablerService] addObserver:self forKeyPath:@"status"
												 options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
												 context:NULL];
	
	[window addSubview:[rootViewController view]];
	[window makeKeyAndVisible];
	[window addSubview:[[StartupAnimation alloc] initWithFrame:window.frame]];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	if ([keyPath compare:@"status"] == 0) {
		IEnablerService *iEnablerService = (IEnablerService *)object;
		
		if (iEnablerService.status == IEnablerServiceUpdating) {
			return;
		}

		if ([iEnablerService errorOccurred]) {
			UIAlertView *alert = [[UIAlertView alloc]
								  initWithTitle:[NSString stringWithFormat:@"Error: %@",[iEnablerService errorReason],nil]
								  message:[NSString stringWithFormat:@"%@",[iEnablerService workaroundHint],nil]
								  delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
			[alert show];
			[alert release];
		}
	}
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != 0) {
		[self updateIEnablerServiceAccess];
	} else {
		if ([IEnablerService sharedIEnablerService].status == IEnablerServiceError )
			[self deduceIEnablerServiceAccess];
	}
}

- (void)deduceIEnablerServiceAccess {
	[[IEnablerService sharedIEnablerService] startDeducingAccessState];
}

- (void)updateIEnablerServiceAccess {
	NSString *username = [[[NSUserDefaults standardUserDefaults] stringForKey:UserNameKey] retain];
	NSString *password = [[[NSUserDefaults standardUserDefaults] stringForKey:PasswordKey] retain];

	if (username != nil && [username length] > 0 && password != nil && [password length] > 0) {
		IEnablerStatus targetStatus = ([[NSUserDefaults standardUserDefaults] boolForKey:AccessStateKey]?IEnablerServiceAccessEnabled:IEnablerServiceAccessDisabled);
		[[IEnablerService sharedIEnablerService]
		 startUpdatingAccessTo:targetStatus
		 forUser:[[NSUserDefaults standardUserDefaults] stringForKey:UserNameKey]
		 withPassword:[[NSUserDefaults standardUserDefaults] stringForKey:PasswordKey]];
	} else {
		UIAlertView *alert = [[UIAlertView alloc]
							  initWithTitle:@"Notice"
							  message:@"Enter both username and password before activating off-campus access."
							  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}

	[username release];
	[password release];
}

// Invoked immediately before the application terminates.
- (void)applicationWillTerminate:(UIApplication *)application {
    //[[NSUserDefaults standardUserDefaults] setBool:NO forKey:AccessStateKey];
	[operationQueue cancelAllOperations];
	[operationQueue waitUntilAllOperationsAreFinished];
}

- (void)dealloc {
	[rootViewController release];
	[window release];
	[super dealloc];
}

@end
